package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.pojo.PageResult;
import cn.itcast.hotel.pojo.RequestParams;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {
    @Autowired
    RestHighLevelClient client;

    @Autowired
    IHotelService hotelService;

    @Override
    public PageResult search(RequestParams params) {
        try {
            // 1. 创建搜索请求
            SearchRequest request = new SearchRequest("hotel");
            // 2. 设置条件  request.source().query();
            buildBasicQuery(params, request);
            // 4. 执行搜索请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            // 5. 解析结果
            return handleResponse(response);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("执行搜索出现异常  异常原因:{}", e.getMessage());
        }
        return null;
    }

    @Override
    public Map<String, List<String>> filters(RequestParams params) {
        // 1. 创建搜索对象
        SearchRequest request = new SearchRequest("hotel");
        //    搜索条件的设置   复用search方法搜索条件
        buildBasicQuery(params, request);
        //    设置聚合处理   要求 按照  品牌  星级  城市 进行terms分桶
        request.source().size(0);
        request.source().aggregation(
                AggregationBuilders.terms("brandAgg")
                        .field("brand")
                        .size(20)
        );
        request.source().aggregation(
                AggregationBuilders.terms("starAgg")
                        .field("starName")
                        .size(20)
        );
        request.source().aggregation(
                AggregationBuilders.terms("cityAgg")
                        .field("city")
                        .size(20)
        );
        // 2. 执行搜索
        try {
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            // 获取聚合结果
            // 3. 解析响应聚合结果
            Aggregations aggregations = response.getAggregations();
            List<String> brandAgg = getAggByName(aggregations, "brandAgg");
            List<String> starAgg = getAggByName(aggregations, "starAgg");
            List<String> cityAgg = getAggByName(aggregations, "cityAgg");
            //    要求 按照  品牌  星级  城市解析聚合结果  封装到map集合中
            Map<String, List<String>> result = new HashMap<>();
            result.put("brand", brandAgg);
            result.put("starName", starAgg);
            result.put("city", cityAgg);
            return result;
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("聚合 获取搜索条件 失败");
        }
    }

    @Override
    public List<String> suggestion(String key) {

        // 1. 创建请求
        SearchRequest request = new SearchRequest("hotel");
        request.source().suggest(new SuggestBuilder().addSuggestion(
                "mySuggestion",
                SuggestBuilders.completionSuggestion("suggestion")
                        .prefix(key)
                        .skipDuplicates(true)
                        .size(10)
        ));
        // 2. 执行请求
        try {
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            Suggest suggest = response.getSuggest();
            // 按照自定义的名称
            CompletionSuggestion suggestion = suggest.getSuggestion("mySuggestion");
            // 所有options
            List<CompletionSuggestion.Entry.Option> options = suggestion.getOptions();
            List<String> list = new ArrayList<>();
            for (CompletionSuggestion.Entry.Option option : options) {
                list.add(option.getText().toString());
            }
            // 3. 解析响应
            return list;
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("自动补全查询出现异常 ");
        }
    }

    @Override
    public void insert(Long hotelId) {
        try {
            Hotel hotel = hotelService.getById(hotelId);

            HotelDoc hotelDoc = new HotelDoc(hotel);

            // 1. 创建
            IndexRequest request = new IndexRequest("hotel");

            request.id(String.valueOf(hotelDoc.getId()));

            request.source(JSON.toJSONString(hotelDoc), XContentType.JSON);
            // 2. 执行

            client.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("删除文档失败 文档id:{}  失败原因:{}", hotelId, e.getMessage());
        }
    }

    @Override
    public void delete(Long hotelId) {
        try {
            // 1. 创建
            DeleteRequest request = new DeleteRequest("hotel", String.valueOf(hotelId));
            // 2. 执行

            client.delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("删除文档失败 文档id:{}  失败原因:{}", hotelId, e.getMessage());
        }
    }

    public List<String> getAggByName(Aggregations aggregations, String name) {
        Terms brandAgg = aggregations.get(name); // 品牌的聚合结果
        List<String> list = new ArrayList<>();
        List<? extends Terms.Bucket> buckets = brandAgg.getBuckets();
        for (Terms.Bucket bucket : buckets) {
            list.add(bucket.getKeyAsString());
        }
        return list;
    }

    public void buildBasicQuery(RequestParams params, SearchRequest request) {
        // 1. 准备bool query条件条件
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        String key = params.getKey();
        if (StringUtils.isNotBlank(key)) {
            // key不为空
            boolQuery.must(QueryBuilders.matchQuery("all", key));
        }
        // 查询term 城市
        if (StringUtils.isNotBlank(params.getCity())) {
            boolQuery.filter(QueryBuilders.termQuery("city", params.getCity()));
        }
        // term 查询 品牌
        if (StringUtils.isNotBlank(params.getBrand())) {
            boolQuery.filter(QueryBuilders.termQuery("brand", params.getBrand()));
        }
        // term 查询  星级
        if (StringUtils.isNotBlank(params.getStarName())) {
            boolQuery.filter(QueryBuilders.termQuery("starName", params.getStarName()));
        }
        if (params.getMinPrice() != null && params.getMaxPrice() != null) {
            boolQuery.filter(QueryBuilders.rangeQuery("price")
                    .gte(params.getMinPrice())
                    .lte(params.getMaxPrice())
            );
        }
        // 3. 分页
        Integer page = params.getPage();
        Integer size = params.getSize();
        request.source().from((page - 1) * size).size(size);


        // 4. 判断是否包含 location  如果包含  设置  按照距离排序
        if (StringUtils.isNotBlank(params.getLocation())) {
            request.source()
                    .sort(SortBuilders.geoDistanceSort("location", new GeoPoint(params.getLocation()))
                            .order(SortOrder.ASC)
                            .unit(DistanceUnit.KILOMETERS) // 距离单位
                    );
        }
        // 5.  当 isAD字段 如果为true 需要重新计算文档得分  : 原有得分 * 5
        // 构建算分函数
        FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery(
                boolQuery, // 原来的bool查询条件
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{ //  可以有多个算分函数
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                QueryBuilders.termQuery("isAD", true),
                                ScoreFunctionBuilders.weightFactorFunction(5) // 算分函数的得分
                        )
                }
        );
        request.source().query(functionScoreQueryBuilder);
    }


    public PageResult handleResponse(SearchResponse response) {
        SearchHits hits = response.getHits();
        long total = hits.getTotalHits().value;// 总数量
        SearchHit[] docArr = hits.getHits();
        List<HotelDoc> list = new ArrayList<>();
        for (SearchHit doc : docArr) {
            HotelDoc hotelDoc = JSON.parseObject(doc.getSourceAsString(), HotelDoc.class);
            // 查询排序距离的值
            Object[] sortValues = doc.getSortValues();
            if (sortValues.length > 0) {
                // 获取排序的值 设置到 距离字段中
                hotelDoc.setDistance(sortValues[0]);
            }
            list.add(hotelDoc);
        }
        return new PageResult(total, list);
    }

}
